<script lang="ts">
    import { Icon } from "../Common/Icons";
    import { useClassList } from "../utils/useClassList";
    import type { TagProps } from "./Tag";

    let { visible = $bindable(true), ...props }: TagProps = $props();

    const value = $derived(props.value || "");
    const classList = $derived(
        useClassList(props, "cm-tag", {
            [`cm-tag-${props.theme}`]: props.theme,
            "cm-tag-has-badge": value !== "",
            "cm-tag-border": props.border,
            "cm-tag-circle": !value && props.circle,
            [`cm-tag-${props.size}`]: props.size,
            "cm-tag-has-avatar": props.avatar,
            "cm-tag-checked": props.checked,
        })
    );

    const _onClose = (e: any) => {
        if (props.onBeforeClose) {
            const ret = props.onBeforeClose(e);
            if (ret) {
                doClose(e);
            }
        } else {
            doClose(e);
        }
    };

    const doClose = (e: any) => {
        visible = false;
        props.onclose?.(e);
    };

    const onClick = (e: any) => {
        props.onclick?.(e);
    };
</script>

{#if visible}
    <!-- svelte-ignore a11y_click_events_have_key_events -->
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div class={classList} style={props.style} onclick={onClick}>
        {@render props.avatar?.()}
        <div class="cm-tag-content">
            <div class="cm-tag-text">{@render props.children?.()}</div>
            {#if props.closable}
                <Icon icon="times" class="cm-tag-close" size={12} onclick={_onClose} />
            {/if}
        </div>
        {#if value !== ""}
            <span class="cm-tag-badge">
                <span class="cm-tag-badge-text">{value}</span>
            </span>
        {/if}
    </div>
{/if}
